package com.fishbone.core.cloud.feign;

import com.fishbone.core.constants.AppConstant;
import com.netflix.hystrix.HystrixCommand;
import feign.Feign;
import feign.RequestInterceptor;
import feign.hystrix.HystrixFeign;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.openfeign.FishBoneHystrixTargeter;
import org.springframework.cloud.openfeign.Targeter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

/**
 * @ClassName FishBoneFeignAutoConfiguration
 * @Author huyaxi
 * @DATE 2020/4/23 16:13
 */
@Configuration
@ConditionalOnClass(Feign.class)
@EnableFishBoneFeign(AppConstant.BASE_PACKAGES)
public class FishBoneFeignAutoConfiguration {


    @Configuration(proxyBeanMethods = false)
    @ConditionalOnClass(name = "feign.hystrix.HystrixFeign")
    protected static class HystrixFeignTargeterConfiguration {
        @Bean
        @ConditionalOnMissingBean
        public Targeter feignTargeter() {
            return new FishBoneHystrixTargeter();
        }

    }


    @Configuration(proxyBeanMethods = false)
    @ConditionalOnClass({ HystrixCommand.class, HystrixFeign.class })
    protected static class HystrixFeignConfiguration {

        @Bean
        @Scope("prototype")
        @ConditionalOnMissingBean
        @ConditionalOnProperty(name = "feign.hystrix.enabled")
        public Feign.Builder feignHystrixBuilder(RequestInterceptor requestInterceptor) {
            return HystrixFeign.builder().requestInterceptor(requestInterceptor);
        }


        @Bean
        @ConditionalOnMissingBean
        public RequestInterceptor requestInterceptor() {
            return new FishBoneRequestHeaderInterceptor();
        }
    }

}
